﻿using Janus.BaseEntitys;
using Janus.Cores.Extension;
using Janus.Cores.Linq;
using Janus.Mes.DTO;
using Janus.Mes.Services.Interface;
using Janus.Mes.VO;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace Janus.Mes.WebClient.Areas.System.Controllers.SysDictionary
{
    public class SysDictionaryController : BaseController
    {
        #region 列表
        /// <summary>
        /// 系统参数设置首页（返回数据列表）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View(new List<SysDictionaryVO>());
        }

        /// <summary>
        /// 返回查询数据
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            return View(GetList(collection));
        }

        public string SubDic(string id, string pk2)
        {
            string result = string.Empty;
            string formtes = "<tr target='SysDictionary_id' rel='{0}' data-tt-id='{1}' data-tt-parent-id='" + id + "'>"
                    + "<td>{2}</td>"
                    + "<td>{3}</td>"
                    + "<td>{4}</td>"
                    + "<td>{5}</td>"
                    + "<td>{6}</td>"
                    + "<td>{7}</td>"
                    + "<td><input id = 'IsSys' name='IsSys' type='checkbox' value='{8}' disabled='true'></td>"
                    + "</tr>\r\n";
            if (pk2.IsNotEmpty())
            {
                Querier query = new Querier();
                query.Where("GroupName!={@0}", "dbo_DecKey");
                query.Where("GroupName={@0}", pk2);
                var subDics = new List<SysDictionaryDTO>(SysDictionaryServices.FindAll(query));
                int i = 1;
                subDics.ForEach(c =>
                {
                    result += string.Format(formtes
                        , c.GroupName
                        , c.GKey
                        , i
                        , c.GroupName
                        , c.DecKey
                        , c.DecValue
                        , c.DecOrder
                        , c.GKey
                        , c.IsSys
                        );
                    i++;
                });
            }
            return result;
        }
        #endregion

        #region 新增修改
        [HttpGet]
        public ActionResult Create(string id)
        {
            SysDictionaryVO sysdictionary = null;
            ViewBag.IsCreate = true;
            if (!string.IsNullOrEmpty(id))
            {
                ViewBag.IsCreate = false;
                Querier query = new Querier("GroupName={@0}", new List<object>() { id });
                var modelList = new List<SysDictionaryDTO>(SysDictionaryServices.FindAll(query));
                if (modelList.HasValues())
                {
                    var voList = AutoMapper.Mapper.DynamicMap<List<SysDictionaryVO>>(modelList);
                    sysdictionary = voList.Find(c => c.DecKey == id);
                    if (sysdictionary != null)
                    {
                        sysdictionary.SubDics = voList.FindAll(c => c.DecKey != id);
                    }
                }
            }
            sysdictionary = sysdictionary ?? base.InitModel<SysDictionaryVO>(sysdictionary);

            return View(sysdictionary);
        }

        /// <summary>
        /// 新增系统参数
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public string Create(FormCollection form)
        {
            try
            {
                var result = false;
                SysDictionaryVO model = new SysDictionaryVO();
                model = base.SetModel<SysDictionaryVO>(form);
                var sysdictionary = model.ToEntity<SysDictionaryDTO>();
                sysdictionary.DecKey = sysdictionary.DecKey ?? sysdictionary.GroupName;
                if (sysdictionary.SubDics.HasValues())
                {
                    sysdictionary.SubDics.ForEach(c =>
                    {
                        c.GroupName = sysdictionary.GroupName;
                        c.GKey = string.Format("{0}_{1}", c.GroupName, c.DecKey);
                        c.IsSys = false;
                    });
                }
                result = SysDictionaryServices.SaveMutil(sysdictionary);
                if (result)
                {
                    ajaxStr = base.AjaxResultSucess;
                }
                else
                {
                    ajaxStr = base.AjaxResultFail;
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = base.AjaxResultFail;
            }
            return "{" + ajaxStr + "}";
        }
        #endregion

        #region 主键是否存在
        [HttpPost]
        public string IsExist()
        {
            string data = Request["data"];
            string targeter = Request["targeter"];
            Querier query = new Querier("GroupName={@0} and DecKey={@1}", new List<object>() { targeter, data });
            bool result = SysDictionaryServices.IsExists(query);
            if (!result)
            {
                ajaxStr = base.AjaxResultSucess;
            }
            else
            {
                ajaxStr = base.AjaxResultFail;
            }
            return "{" + ajaxStr + "}";
        }

        [HttpPost]
        public string IsGroupNameExist()
        {
            string data = Request["data"];
            string targeter = Request["targeter"];
            Querier query = new Querier("GroupName={@0}", new List<object>() { data });
            bool result = SysDictionaryServices.IsExists(query);
            if (!result)
            {
                ajaxStr = base.AjaxResultSucess;
            }
            else
            {
                ajaxStr = base.AjaxResultFail;
            }
            return "{" + ajaxStr + "}";
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除系统参数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string Delete(object id, object pk2)
        {
            try
            {
                var result = SysDictionaryServices.Delete(id, pk2);
                if (result)
                {
                    ajaxStr = base.AjaxDeleteSucess;
                }
                else
                {
                    ajaxStr = base.AjaxResultFail;
                }
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = base.AjaxResultFail;
            }

            return "{" + ajaxStr + "}";
        }
        #endregion

        #region 私有方法
        protected IEnumerable<SysDictionaryVO> GetList(FormCollection collection)
        {
            var searchParma = base.SearchPara<SysDictionaryDTO>(collection);
            searchParma.Queriers.Where("GroupName={@0}", "dbo_DecKey");
            if (searchParma.Model.GroupName.IsNotEmpty())
            {
                searchParma.Queriers.Where("GroupName.Contains({@0})", searchParma.Model.GroupName);
            }
            if (searchParma.Model.DecValue.IsNotEmpty())
            {
                searchParma.Queriers.Where("DecValue=({@0})", searchParma.Model.DecValue);
            }
            //可以继续判断 增加查询条件

            var result = base.FindAll<SysDictionaryDTO>(searchParma, SysDictionaryServices);
            if (!result.ErrorMessage.IsNotEmpty())
            {
                var list = AutoMapper.Mapper.DynamicMap<List<SysDictionaryVO>>(result.Result);
                return list;
            }
            else
            {
                return new List<SysDictionaryVO>();
            }
        }
        #endregion
    }
}